jQuery(function($) {
    $(document).bind('keydown.facebox', function(e) {
        if (e.keyCode == 27) {
            $.facebox.close();
        }
        return true;
    })
});
(function($) {
    $.facebox = function(data, klass) {
        $.facebox.loading()

        if (data.ajax) fillFaceboxFromAjax(data.ajax)
        else if (data.image) fillFaceboxFromImage(data.image)
        else if (data.div) fillFaceboxFromHref(data.div)
        else if ($.isFunction(data)) data.call($)
        else $.facebox.reveal(data, klass)
    }

    /*
    * Public, $.facebox methods
    */

    $.extend($.facebox, {
        settings: {
            opacity: 0.1,
            pageNum: 0,
            overlay: false,
            loadingImage: '../images/popup/loading.gif',
            closeImage: '../images/popup/close.png',
            imageTypes: ['png', 'jpg', 'jpeg', 'gif'],
            faceboxHtml: '<div class="facebox selectFree" style="display:none;"> \
		<table class="shadow"> \
			<tr> \
				<td class="shadowTL"></td> \
				<td class="shadowT"></td> \
				<td class="shadowTR"></td> \
			</tr> \
			<tr> \
				<td class="shadowL"></td> \
				<td class="content"></td> \
				<td class="shadowR"></td> \
			</tr> \
			<tr> \
				<td class="shadowBL"></td> \
				<td class="shadowB"></td> \
				<td class="shadowBR"></td> \
			</tr> \
		</table> \
		<div class="clear"></div> \
		<!--[if lte IE 6.5]><iframe></iframe><![endif]--> \
    </div>',
            overlay: '<div id="facebox_overlay" class="overlay"></div>'
        },

        loading: function() {
            init();

            if ($('#page_' + $.facebox.settings.pageNum + ' .loading').length == 1) return true;

            $('#page_' + $.facebox.settings.pageNum + ' .content').empty();
            $('#page_' + $.facebox.settings.pageNum).append('<div class="loading"><img src="' + $.facebox.settings.loadingImage + '"/></div>');

            $('#page_' + $.facebox.settings.pageNum).css({
                top: getPageScroll()[1] + (getPageHeight() / 100),
                //top: 200,
                left: 385.5
            }).show();


            $('#page_' + $.facebox.settings.pageNum).trigger('loading.facebox')
        },

        reveal: function(data, klass) {
            $('#page_' + $.facebox.settings.pageNum).trigger('beforeReveal.facebox')
            if (klass) $('#page_' + $.facebox.settings.pageNum + ' .content').addClass(klass)
            $('#page_' + $.facebox.settings.pageNum + ' .content').append(data)
            $('#page_' + $.facebox.settings.pageNum + ' .loading').remove()
            $('#page_' + $.facebox.settings.pageNum + ' .content').fadeIn('normal')
            var h = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight;
            var objH = $('#page_' + $.facebox.settings.pageNum).height();
            if (objH > h - 5) {
                var otherH = objH - $('#page_' + $.facebox.settings.pageNum).find(".tableWrap").height();
                objH = h - 5;
                try {
                    var tmp = $('#page_' + $.facebox.settings.pageNum).find(".tableWrap");
                    if (tmp.attr("SpSign") != "NoScorll") {
                        tmp.height(objH - otherH).addClass("overHeightScroll");
                    }
                }
                catch (err) {
                }
            }

            var tempTop = (h - objH) / 2 + document.documentElement.scrollTop;
            if (tempTop < 5) {
                tempTop = 5;
            }
            $('#page_' + $.facebox.settings.pageNum).css({
                'left': $(window).width() / 2 - ($('#page_' + $.facebox.settings.pageNum).width() / 2),
                'top': tempTop,
                'z-index': 800 + $.facebox.settings.pageNum * 2 + 1
            })
            $('#page_' + $.facebox.settings.pageNum).trigger('reveal.facebox').trigger('afterReveal.facebox')

            $.facebox.settings.pageNum = $.facebox.settings.pageNum;
            if (typeof revealCallBack !== "undefined" && revealCallBack)
                revealCallBack();

        },

        close: function(o) {
            if ($.facebox.settings.pageNum == 0) {
                return false;
            }
            //if (o == ".facebox .content") {

            $('#page_' + $.facebox.settings.pageNum).remove();
            $("#facebox_overlay_" + $.facebox.settings.pageNum).remove();
            //$(o).parents('.facebox').remove();
            //$('.overlay').remove();
            //}
            //else {
            //    var pageNum = $(o).parents('.facebox').attr("id").substr(5);
            //    $(o).parents('.facebox').remove();
            //    $("#facebox_overlay_" + pageNum).remove();
            // }
            while ($("#facebox_overlay_" + $.facebox.settings.pageNum).length == 0 && $.facebox.settings.pageNum > 0) {
                $.facebox.settings.pageNum--;
            }
        }
    })

    /*
    * Public, $.fn methods
    */

    $.fn.facebox = function(settings) {
        init(settings)

        function clickHandler() {
            $.facebox.loading(true)

            // support for rel="facebox.inline_popup" syntax, to add a class
            // also supports deprecated "facebox[.inline_popup]" syntax
            var klass = this.rel.match(/facebox\[?\.(\w+)\]?/)
            if (klass) klass = klass[1]

            fillFaceboxFromHref(this.href, klass)
            return false
        }

        return this.click(clickHandler)
    }

    /*
    * Private methods
    */

    // called one time to setup facebox on this page
    function init(settings) {
        //if ($.facebox.settings.inited) return true
        //else $.facebox.settings.inited = true

        //$(document).trigger('init.facebox')
        makeCompatible()

        var imageTypes = $.facebox.settings.imageTypes.join('|')
        $.facebox.settings.imageTypesRegexp = new RegExp('\.' + imageTypes + '$', 'i')

        if (settings) $.extend($.facebox.settings, settings);

        $.facebox.settings.pageNum++;
        var newpage = $.facebox.settings.faceboxHtml;
        var newoverlay = $($.facebox.settings.overlay);
        newoverlay.css("z-index", 800 + $.facebox.settings.pageNum * 2);
        newoverlay.attr("id", "facebox_overlay_" + $.facebox.settings.pageNum);
        newpage = newpage.substring(0, 4) + ' id="page_' + $.facebox.settings.pageNum + '"' + newpage.substring(4, newpage.length);
        $('body').append(newpage).append(newoverlay);
        $("#facebox_overlay_" + $.facebox.settings.pageNum).css('opacity', $.facebox.settings.opacity);

        var preload = [new Image(), new Image()]
        preload[0].src = $.facebox.settings.closeImage
        preload[1].src = $.facebox.settings.loadingImage

    }

    // getPageScroll() by quirksmode.com
    function getPageScroll() {
        var xScroll, yScroll;
        if (self.pageYOffset) {
            yScroll = self.pageYOffset;
            xScroll = self.pageXOffset;
        } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
            yScroll = document.documentElement.scrollTop;
            xScroll = document.documentElement.scrollLeft;
        } else if (document.body) {// all other Explorers
            yScroll = document.body.scrollTop;
            xScroll = document.body.scrollLeft;
        }
        return new Array(xScroll, yScroll)
    }

    // Adapted from getPageSize() by quirksmode.com
    function getPageHeight() {
        var windowHeight
        if (self.innerHeight) {	// all except Explorer
            windowHeight = self.innerHeight;
        } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
            windowHeight = document.documentElement.clientHeight;
        } else if (document.body) { // other Explorers
            windowHeight = document.body.clientHeight;
        }
        return windowHeight
    }

    // Backwards compatibility
    function makeCompatible() {
        var $s = $.facebox.settings

        $s.loadingImage = $s.loading_image || $s.loadingImage
        $s.closeImage = $s.close_image || $s.closeImage
        $s.imageTypes = $s.image_types || $s.imageTypes
        $s.faceboxHtml = $s.facebox_html || $s.faceboxHtml
    }

    // Figures out what you want to display and displays it
    // formats are:
    //     div: #id
    //   image: blah.extension
    //    ajax: anything else
    function fillFaceboxFromHref(href, klass) {
        // div
        if (href.match(/#/)) {
            var url = window.location.href.split('#')[0]
            var target = href.replace(url, '')
            $.facebox.reveal($(target).clone().show(), klass)

            // image
        } else if (href.match($.facebox.settings.imageTypesRegexp)) {
            fillFaceboxFromImage(href, klass)
            // ajax
        } else {
            fillFaceboxFromAjax(href, klass)
        }
    }

    function fillFaceboxFromImage(href, klass) {
        var image = new Image()
        image.onload = function() {
            $.facebox.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass)
        }
        image.src = href
    }

    function fillFaceboxFromAjax(href, klass) {
        $.get(href, function(data) { $.facebox.reveal(data, klass) })
    }

    /*
    * Bindings
    */

    $('#page_' + $.facebox.settings.pageNum).bind('close.facebox', function() {
        $(document).unbind('keydown.facebox')
        $('#page_' + $.facebox.settings.pageNum + '').fadeOut(function() {
            $('#page_' + $.facebox.settings.pageNum + ' .loading').remove();
        });
    })

})(jQuery);
